import { useState, useEffect } from 'react';
import {
  Button,
  Input,
  Label,
  Text,
  Spinner,
  Table,
  TableHeader,
  TableRow,
  TableHead,
  TableBody,
  TableCell,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
  Checkbox
} from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';
import { Classroom, getClassrooms, addClassroom, updateClassroom, deleteClassroom } from '../mock/classroomData';
import { dashboardDataManager } from '../services/dashboardService';

export default function ClassroomManagementPage() {
  const { session } = useSession();
  const [classrooms, setClassrooms] = useState<Classroom[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentClassroom, setCurrentClassroom] = useState<Classroom | null>(null);
  const [isAddOpen, setIsAddOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [form, setForm] = useState({
    name: '',
    location: '',
    capacity: 30,
    type: '普通教室',
    equipment: '投影仪',
    available: true,
  });
  const [alert, setAlert] = useState('');
  const [showAlert, setShowAlert] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');

  // 分页和批量删除相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [selectedClassrooms, setSelectedClassrooms] = useState<number[]>([]);
  const [selectAll, setSelectAll] = useState(false);

  // 教室类型选项
  const classroomTypes = ['普通教室', '多媒体教室', '实验室', '阶梯教室', '会议室'];

  // 权限检查
  const canEdit = session?.userRole === 'admin' || session?.userRole === 'user';
  const canDelete = session?.userRole === 'admin';
  const canAdd = session?.userRole === 'admin';

  useEffect(() => {
    loadClassrooms();
  }, []);

// 1. 修改加载教室数据函数
const loadClassrooms = async () => {
  setLoading(true);
  try {
    // 首先尝试从localStorage加载
    const savedClassrooms = localStorage.getItem('classrooms');
    if (savedClassrooms) {
      setClassrooms(JSON.parse(savedClassrooms));
    } else {
      // 如果localStorage没有，调用API获取
      const classroomsData = await getClassrooms();
      setClassrooms(classroomsData);
      // 保存到localStorage
      localStorage.setItem('classrooms', JSON.stringify(classroomsData));
    }
  } catch (error) {
    console.error('加载教室列表失败:', error);
    setAlert('加载教室列表失败');
    setShowAlert(true);
  } finally {
    setLoading(false);
  }
};

// 2. 修改添加教室函数
const handleAdd = async () => {
  try {
    // 调用mock API添加教室
    const { name, location, capacity, type, equipment, available } = form;
    const newClassroom = await addClassroom({
      name,
      location,
      capacity: Number(capacity), // 确保capacity是数字类型
      type,
      equipment,
      available
    });
    
    // 更新本地状态
    const updatedClassrooms = [...classrooms, newClassroom];
    setClassrooms(updatedClassrooms);
    
    // 保存到localStorage
    localStorage.setItem('classrooms', JSON.stringify(updatedClassrooms));
    
    // 通知监听器数据已更新
    dashboardDataManager.notifyListeners();
    
    setIsAddOpen(false);
    setAlert('添加教室成功');
    setShowAlert(true);
  } catch (error) {
    console.error('添加教室失败:', error);
    setAlert('添加教室失败');
    setShowAlert(true);
  }
};

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value, type, checked } = e.target;
    setForm(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  // 重置表单
  const resetForm = () => {
    setForm({
      name: '',
      location: '',
      capacity: 30,
      type: '普通教室',
      equipment: '投影仪',
      available: true,
    });
  };

  // 打开添加对话框
  const handleAddOpen = () => {
    resetForm();
    setIsAddOpen(true);
  };

  // 打开编辑对话框
  const handleEditOpen = (classroom: Classroom) => {
    setCurrentClassroom(classroom);
    setForm({
      name: classroom.name,
      location: classroom.location,
      capacity: classroom.capacity,
      type: classroom.type,
      equipment: classroom.equipment,
      available: classroom.available,
    });
    setIsEditOpen(true);
  };

  // 打开删除对话框
  const handleDeleteOpen = (classroom: Classroom) => {
    setCurrentClassroom(classroom);
    setIsDeleteOpen(true);
  };

  // 3. 修改编辑教室函数
const handleEdit = async () => {
  if (!currentClassroom) return;
  try {
    // 调用mock API编辑教室
    const { name, location, capacity, type, equipment, available } = form;
    const updatedClassroom = await updateClassroom(currentClassroom.id, {
      name,
      location,
      capacity: Number(capacity), // 确保capacity是数字类型
      type,
      equipment,
      available
    });
    
    // 更新本地状态
    const updatedClassrooms = classrooms.map(classroom => 
      classroom.id === updatedClassroom.id ? updatedClassroom : classroom
    );
    setClassrooms(updatedClassrooms);
    
    // 保存到localStorage
    localStorage.setItem('classrooms', JSON.stringify(updatedClassrooms));
    
    // 通知监听器数据已更新
    dashboardDataManager.notifyListeners();
    
    setIsEditOpen(false);
    setAlert('编辑教室成功');
    setShowAlert(true);
  } catch (error) {
    console.error('编辑教室失败:', error);
    setAlert('编辑教室失败');
    setShowAlert(true);
  }
};

  // 4. 修改删除教室函数
const handleDelete = async () => {
  if (!currentClassroom) return;
  try {
    // 调用mock API删除教室
    await deleteClassroom(currentClassroom.id);
    
    // 更新本地状态
    const updatedClassrooms = classrooms.filter(classroom => classroom.id !== currentClassroom.id);
    setClassrooms(updatedClassrooms);
    
    // 保存到localStorage
    localStorage.setItem('classrooms', JSON.stringify(updatedClassrooms));
    
    // 通知监听器数据已更新
    dashboardDataManager.notifyListeners();
    
    setIsDeleteOpen(false);
    setAlert('删除教室成功');
    setShowAlert(true);
  } catch (error) {
    console.error('删除教室失败:', error);
    setAlert('删除教室失败');
    setShowAlert(true);
  }
};

  // 处理批量删除
  const handleBatchDelete = async () => {
    if (selectedClassrooms.length === 0) {
      setAlert('请选择要删除的教室');
      setShowAlert(true);
      return;
    }

    try {
      // 模拟批量删除API调用
      for (const classroomId of selectedClassrooms) {
        await deleteClassroom(classroomId);
      }
      
      const updatedClassrooms = classrooms.filter(classroom => !selectedClassrooms.includes(classroom.id));
      setClassrooms(updatedClassrooms);
      setSelectedClassrooms([]);
      setSelectAll(false);
      
      // 保存到localStorage
      localStorage.setItem('classrooms', JSON.stringify(updatedClassrooms));
      
      // 通知监听器数据已更新
      dashboardDataManager.notifyListeners();
      
      setAlert(`成功删除 ${selectedClassrooms.length} 个教室`);
      setShowAlert(true);
    } catch (error) {
      console.error('批量删除教室失败:', error);
      setAlert('批量删除教室失败');
      setShowAlert(true);
    }
  };

  // 教室选择处理
  const handleSelectClassroom = (classroomId: number, checked: boolean) => {
    if (checked) {
      setSelectedClassrooms([...selectedClassrooms, classroomId]);
    } else {
      setSelectedClassrooms(selectedClassrooms.filter(id => id !== classroomId));
      setSelectAll(false);
    }
  };

  // 全选处理
  const handleSelectAll = (checked: boolean) => {
    setSelectAll(checked);
    if (checked) {
      setSelectedClassrooms(filteredClassrooms.map(classroom => classroom.id));
    } else {
      setSelectedClassrooms([]);
    }
  };

  // 过滤教室列表
  const filteredClassrooms = classrooms.filter(classroom =>
    classroom.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    classroom.location.toLowerCase().includes(searchTerm.toLowerCase()) ||
    classroom.type.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // 分页逻辑
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredClassrooms.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.max(1, Math.ceil(filteredClassrooms.length / itemsPerPage));

  // 分页处理函数
  const goToPage = (page: number) => {
    setCurrentPage(Math.max(1, Math.min(page, totalPages)));
  };

  const nextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage(currentPage + 1);
    }
  };

  const prevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  const handleItemsPerPageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setItemsPerPage(parseInt(e.target.value));
    setCurrentPage(1);
  };

  return (
    <div className="p-6 bg-white">
      {/* 页面标题和操作按钮 */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6 gap-4">
        <Text className="text-2xl font-bold text-gray-900">教室管理</Text>
        <div className="flex items-center gap-3">
          {/* 批量删除按钮 */}
          {canDelete && (
            <Button 
              variant="destructive" 
              onClick={handleBatchDelete}
              disabled={selectedClassrooms.length === 0}
            >
              批量删除 ({selectedClassrooms.length})
            </Button>
          )}
          {canAdd && (
            <Button variant="primary" onClick={handleAddOpen}>
              添加教室
            </Button>
          )}
        </div>
      </div>

      {/* 搜索 */}
      <div className="mb-6">
        <div className="relative max-w-md">
          <Input
            type="text"
            placeholder="搜索教室名称、位置或类型..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
          <span className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">🔍</span>
        </div>
      </div>

      {/* 警告提示 */}
      {showAlert && (
        <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
          <Text className="text-blue-700">{alert}</Text>
          <Button 
           variant="ghost"
            size="sm" 
            onClick={() => setShowAlert(false)}
            className="absolute right-3 top-2 text-blue-500"
          >
            ×
          </Button>
        </div>
      )}

      {/* 教室列表表格 */}
      <div className="overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-16">
                <Checkbox
                  checked={selectAll}
                  onChange={(e) => handleSelectAll(e.target.checked)}
                  disabled={filteredClassrooms.length === 0}
                />
              </TableHead>
              <TableHead className="w-16">ID</TableHead>
              <TableHead>教室名称</TableHead>
              <TableHead>位置</TableHead>
              <TableHead>容量</TableHead>
              <TableHead>类型</TableHead>
              <TableHead>设备</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={9} className="text-center py-8">
                  <Spinner className="mx-auto" />
                </TableCell>
              </TableRow>
            ) : currentItems.length === 0 ? (
              <TableRow>
                <TableCell colSpan={9} className="text-center py-8">
                  暂无教室数据
                </TableCell>
              </TableRow>
            ) : (
              currentItems.map((classroom) => (
                <TableRow key={classroom.id}>
                  <TableCell>
                    <Checkbox
                      checked={selectedClassrooms.includes(classroom.id)}
                      onChange={(e) => handleSelectClassroom(classroom.id, e.target.checked)}
                    />
                  </TableCell>
                  <TableCell>{classroom.id}</TableCell>
                  <TableCell>{classroom.name}</TableCell>
                  <TableCell>{classroom.location}</TableCell>
                  <TableCell>{classroom.capacity}</TableCell>
                  <TableCell>{classroom.type}</TableCell>
                  <TableCell>{classroom.equipment}</TableCell>
                  <TableCell>
                    <span className={`px-2 py-1 rounded text-xs ${classroom.available ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                      {classroom.available ? '可用' : '不可用'}
                    </span>
                  </TableCell>
                  <TableCell>
                    <div className="flex space-x-2">
                      {canEdit && (
                        <Button  variant="ghost" onClick={() => handleEditOpen(classroom)}>
                          编辑
                        </Button>
                      )}
                      {canDelete && (
                        <Button variant="ghost" color="red" onClick={() => handleDeleteOpen(classroom)}>
                          删除
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 分页控制 */}
      <div className="mt-6 flex flex-col md:flex-row justify-between items-center gap-4">
        <div className="text-sm text-gray-600">
          显示 {indexOfFirstItem + 1} - {Math.min(indexOfLastItem, filteredClassrooms.length)} 共 {filteredClassrooms.length} 项
          <select 
            className="ml-2 px-2 py-1 border border-gray-300 rounded-md text-sm"
            value={itemsPerPage}
            onChange={handleItemsPerPageChange}
          >
            <option value="5">5条/页</option>
            <option value="10">10条/页</option>
            <option value="20">20条/页</option>
            <option value="50">50条/页</option>
          </select>
        </div>
        <div className="flex items-center gap-2">
          <Button 
            variant="ghost" 
            size="sm" 
            onClick={prevPage} 
            disabled={currentPage === 1}
          >
            上一页
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "primary" : "ghost"}
                size="sm"
                onClick={() => goToPage(pageNum)}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button 
            variant="ghost" 
            size="sm" 
            onClick={nextPage} 
            disabled={currentPage === totalPages}
          >
            下一页
          </Button>
        </div>
      </div>

      {/* 添加教室对话框 */}
      <Dialog open={isAddOpen} onOpenChange={setIsAddOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>添加教室</DialogTitle>
            <DialogDescription>
              请填写教室信息
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="name" className="text-right">教室名称</Label>
              <Input
                id="name"
                name="name"
                value={form.name}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="location" className="text-right">位置</Label>
              <Input
                id="location"
                name="location"
                value={form.location}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="capacity" className="text-right">容量</Label>
              <Input
                id="capacity"
                name="capacity"
                type="number"
                min="1"
                value={form.capacity}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="type" className="text-right">类型</Label>
              <select
                id="type"
                name="type"
                value={form.type}
                onChange={handleInputChange}
                className="col-span-3 border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              >
                {classroomTypes.map(type => (
                  <option key={type} value={type}>{type}</option>
                ))}
              </select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="equipment" className="text-right">设备</Label>
              <Input
                id="equipment"
                name="equipment"
                value={form.equipment}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">可用状态</Label>
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="available"
                  name="available"
                  checked={form.available}
                  onChange={handleInputChange}
                  className="w-4 h-4 text-blue-600 bg-gray-100 rounded border-gray-300 focus:ring-blue-500"
                />
                <Label htmlFor="available" className="ml-2">可用</Label>
              </div>
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button onClick={handleAdd}>添加</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 编辑教室对话框 */}
      <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>编辑教室</DialogTitle>
            <DialogDescription>
              请修改教室信息
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-name" className="text-right">教室名称</Label>
              <Input
                id="edit-name"
                name="name"
                value={form.name}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-location" className="text-right">位置</Label>
              <Input
                id="edit-location"
                name="location"
                value={form.location}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-capacity" className="text-right">容量</Label>
              <Input
                id="edit-capacity"
                name="capacity"
                type="number"
                min="1"
                value={form.capacity}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-type" className="text-right">类型</Label>
              <select
                id="edit-type"
                name="type"
                value={form.type}
                onChange={handleInputChange}
                className="col-span-3 border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              >
                {classroomTypes.map(type => (
                  <option key={type} value={type}>{type}</option>
                ))}
              </select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-equipment" className="text-right">设备</Label>
              <Input
                id="edit-equipment"
                name="equipment"
                value={form.equipment}
                onChange={handleInputChange}
                className="col-span-3"
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">可用状态</Label>
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="edit-available"
                  name="available"
                  checked={form.available}
                  onChange={handleInputChange}
                  className="w-4 h-4 text-blue-600 bg-gray-100 rounded border-gray-300 focus:ring-blue-500"
                />
                <Label htmlFor="edit-available" className="ml-2">可用</Label>
              </div>
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button onClick={handleEdit}>保存</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除教室对话框 */}
      <Dialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确定要删除该教室吗？此操作不可撤销。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button variant="destructive" onClick={handleDelete}>
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}